package com.gscitysfy.cus.drain.modules.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cus.drain.config.BusinessException;
import com.gscitysfy.cus.drain.modules.command.entity.DangerSituationManage;
import com.gscitysfy.cus.drain.modules.command.entity.InstructCar;
import com.gscitysfy.cus.drain.modules.command.mapper.DangerSituationManageMapper;
import com.gscitysfy.cus.drain.modules.command.mapper.InstructCarMapper;
import com.gscitysfy.cus.drain.modules.resource.convert.ResourceCarConvert;
import com.gscitysfy.cus.drain.modules.resource.dto.ResourceCarDto;
import com.gscitysfy.cus.drain.modules.resource.entity.ResourceCar;
import com.gscitysfy.cus.drain.modules.resource.mapper.ResourceCarMapper;
import com.gscitysfy.cus.drain.modules.resource.service.IResourceCarService;
import com.gscitysfy.cus.drain.modules.resource.vo.ResourceCarQuery;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 防汛车辆表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2022-10-23 15:27:02
 */
@AllArgsConstructor
@Service
public class ResourceCarServiceImpl extends ServiceImpl<ResourceCarMapper, ResourceCar> implements IResourceCarService {


    private final ResourceCarConvert resourceCarConvert;

    private final ResourceCarMapper resourceCarMapper;

    private final InstructCarMapper instructCarMapper;

    private final DangerSituationManageMapper dangerSituationManageMapper;

    @Override
    public IPage<ResourceCarDto> fetchPage(Page page, ResourceCarQuery query) {
        LambdaQueryWrapper<ResourceCar> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper = buildQueryWrapper(queryWrapper, query);
        Page<ResourceCar> resourceCarPage = this.page(page, queryWrapper);
        return resourceCarPage.convert(resourceCarConvert::toDto);
    }

    @Override
    public List<ResourceCarDto> list(Long dangerSituationId) {
        List<ResourceCarDto> resourceCarDtoList = new ArrayList<>();
        if (Objects.isNull(dangerSituationId)) {
            throw new BusinessException("缺少险情管理信息");
        }
        DangerSituationManage dangerSituationManage = dangerSituationManageMapper.selectById(dangerSituationId);
        LambdaQueryWrapper<ResourceCar> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ResourceCar::getCmUsable, false);
        List<ResourceCar> resourceCarList = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(resourceCarList)) {
            resourceCarList.forEach(resourceCar -> {
                resourceCarDtoList.add(resourceCarConvert.toDto(resourceCar, dangerSituationManage));
            });
        }
        return resourceCarDtoList;
    }

    @Override
    public ResourceCarDto getById(Long cmKid) {
        ResourceCar resourceCar = baseMapper.selectById(cmKid);
        return resourceCarConvert.toDto(resourceCar);
    }

    @Override
    public List<ResourceCarDto> fetchGis() {
        //未分配车辆
        List<ResourceCar> unAssignedResourceCarList = resourceCarMapper.fetchUnAssignedGis();
        unAssignedResourceCarList.forEach(unAssignedResourceCar -> {
            unAssignedResourceCar.setAssignedFlag(false);
        });
        List<ResourceCar> resourceCarList = new ArrayList<>(unAssignedResourceCarList);
        //已分配车辆
        List<ResourceCar> assignedResourceCarList = resourceCarMapper.fetchAssignedGis();
        assignedResourceCarList.forEach(assignedResourceCar -> {
            assignedResourceCar.setAssignedFlag(true);
        });
        resourceCarList.addAll(assignedResourceCarList);
        return resourceCarConvert.toDtoList(resourceCarList);
    }

    @Override
    public List<ResourceCarDto> fetchInIdList(List<Long> idList) {
        LambdaQueryWrapper<ResourceCar> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(ResourceCar::getCmKid, idList);
        List<ResourceCar> resourceCarList = baseMapper.selectList(queryWrapper);
        return resourceCarConvert.toDtoList(resourceCarList);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean saveOrUpdate(ResourceCarDto dto) {
        if (Objects.isNull(dto.getCmKid())) {
            ResourceCar resourceCar = new ResourceCar();
            //geom
            completeGeom(resourceCar, dto);
            resourceCarConvert.toEntity(resourceCar, dto);
            return this.save(resourceCar);
        } else {
            ResourceCar resourceCar = baseMapper.selectById(dto.getCmKid());
            //geom
            completeGeom(resourceCar, dto);
            resourceCarConvert.toEntity(resourceCar, dto);
            return this.updateById(resourceCar);
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean delete(List<Long> idList) {
        List<ResourceCar> resourceCarList = new ArrayList<>();
        idList.forEach(id -> {
            ResourceCar resourceCar = baseMapper.selectById(id);
            //判断是否还有未完成的任务
            List<InstructCar> instructCarList = instructCarMapper.fetchByUsefulResourceCar(id);
            if (CollectionUtils.isNotEmpty(instructCarList)) {
                throw new BusinessException(String.format("防汛车辆：%s，存在未完成的任务无法删除", resourceCar.getCarName()));
            }
            resourceCar.setCmUsable(true);
            resourceCarList.add(resourceCar);
        });
        return this.updateBatchById(resourceCarList);
    }

    /**
     * query组装
     *
     * @param queryWrapper
     * @param query
     * @return
     */
    public LambdaQueryWrapper<ResourceCar> buildQueryWrapper(LambdaQueryWrapper<ResourceCar> queryWrapper, ResourceCarQuery query) {
        if (Objects.nonNull(query.getCmRegflag())) {
            queryWrapper.eq(ResourceCar::getCmRegflag, String.valueOf(query.getCmRegflag()));
        }
        if (StringUtils.isNotEmpty(query.getCarName())) {
            queryWrapper.like(ResourceCar::getCarName, query.getCarName());
        }
        if (StringUtils.isNotEmpty(query.getCarPlate())) {
            queryWrapper.like(ResourceCar::getCarPlate, query.getCarPlate());
        }
        if (StringUtils.isNotEmpty(query.getResponser())) {
            queryWrapper.like(ResourceCar::getResponser, query.getResponser());
        }
        //删除标识
        queryWrapper.eq(ResourceCar::getCmUsable, query.getCmUsable());
        //更新时间倒排
        queryWrapper.orderByDesc(ResourceCar::getCmUptime);
        return queryWrapper;
    }

    /**
     * 基于经纬度生成Geom
     *
     * @param resourceCar
     * @param dto
     * @return
     */
    public ResourceCar completeGeom(ResourceCar resourceCar, ResourceCarDto dto) {
        BigDecimal lgtd = dto.getLgtd();
        BigDecimal lttd = dto.getLttd();
        if (Objects.nonNull(dto.getLgtd()) && Objects.nonNull(dto.getLttd())) {
            lgtd = lgtd.setScale(6, RoundingMode.HALF_UP);
            lttd = lttd.setScale(6, RoundingMode.HALF_UP);
            String theGeom = "POINT(" + lgtd + " " + lttd + ")";
            resourceCar.setCmGeom(theGeom);
        }
        return resourceCar;
    }
}
